import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import legacy from '@vitejs/plugin-legacy';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
import path from 'path';

const pathSrc = path.resolve(__dirname, 'src');

// https://vitejs.dev/config/
export default defineConfig( ({mode}) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_PORT, VITE_APP_BASE_API, VITE_API } = env;
  return {
    css: {
      postcss: {
        plugin: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      },
      preprocessOptions: {
        scss: {
          additionalData: `@import "@/assets/styles/index.scss";`,
          javascriptEnabled: true,
          charset: false
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathSrc
        },
        {
          find: '@element-plus/icons/lib/dist$',
          replacement: './src/plugins/icon.js'
        }

      ]
    },
    plugins: [
      vue(),
      VueSetupExtend(),
      AutoImport({
        //安装两行后你会发现在组件中不用再导入ref，reactive等
        imports: ['vue', 'vue-router', 'vuex', 'pinia'],
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver({importStyle:true})]
      }),

      legacy({
        targets: ['cover 99.5%']
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: {
          plugins: [
            {
              name: 'removeAttrs',
              params: { attrs: ['class', 'data-name', 'fill', 'stroke'] }
            }
          ]
        }
      })
    ],
    optimizeDeps: {
      include: ['element-plus']
    },
    server: {
      host: '0.0.0.0',
      port: VITE_PORT,
      open: true,
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_API,
          changeOrigin: true,
          rewrite: path => path.replace(new RegExp('^' + VITE_APP_BASE_API), '')
        }
      }
    }

  }
})
